package com.vermouth.filter;

import com.bachongLightNovel.constant.RedisConstant;
import com.bachongLightNovel.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @author vermouth
 */
@Slf4j
@Component
public class RefreshTimeFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 刷新token过期时间
     * @param exchange:
    	 * @param chain:
     * @return Mono<Void>
     * @author vermouth
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("刷新登录时间");
        ServerHttpRequest request = exchange.getRequest();

        log.info(request.getPath().toString());
        //登录接口直接放过
        if (request.getURI().getPath().contains("login")) {
            return chain.filter(exchange);
        }
        //放过注册接口
        if (request.getURI().getPath().contains("register")){
            return chain.filter(exchange);
        }
        //放过文件上传接口
        if (request.getURI().getPath().contains("upload")){
            return chain.filter(exchange);
        }
        //获取token
        String token = request.getHeaders().getFirst("Token");
        Claims claims = JwtUtils.parseJWT(token);
        String username = (String) claims.get("username");
        //刷新登录时间
        stringRedisTemplate.expire(RedisConstant.BACHONG_LOGIN_TOKEN+username,30, TimeUnit.MINUTES);

        return chain.filter(exchange);
    }

    /**
     * 设置过滤顺序
     * @param :
     * @return int
     * @author vermouth
     */
    @Override
    public int getOrder() {
        return 2;
    }
}
